package Tree;

/**
 * 作者:hfj
 * 功能:110.平衡二叉树
 * 日期: 2025/10/24 20:48
 */
public class IsBalanced {

    public boolean isBalanced(TreeNode root) {
        return balance(root) != -1;
    }

    public int balance(TreeNode root){
        if (root == null){
            return 0;
        }
        int left = balance(root.left);
        if (left == -1){
            return -1;
        }
        int right = balance(root.right);
        if (right == -1){
            return -1;
        }
        //高度大于2不是平衡二叉树
        if (Math.abs(left - right) > 1){
            return -1;
        }
        return Math.max(left, right) + 1;
    }
}
